var express = require("express");
var router = express.Router();
const alipaySdk = require("./parseisdk");
const axios = require("axios");
const AlipayFormData = require("alipay-sdk/lib/form").default;
const {
  salonModel,
  serviceModel,
  stylistModel,
  orderModel,
  packageModel,
  userModel,
  reviewModel,
} = require("../../model/model");

router.post("/adduser", async (req, res) => {
  await userModel.create(req.body);
  res.send({ code: 200 });
});

router.get("/getuser", async (req, res) => {
  let data = await userModel.find();
  res.send({ code: 200, data });
});

router.post("/addsalon", async (req, res) => {
  await salonModel.create(req.body);
  res.send({ code: 200 });
});
router.get("/getsalon", async (req, res) => {
  let data = await salonModel.find();
  res.send({ code: 200, data });
});

router.post("/addservice", async (req, res) => {
  await serviceModel.create(req.body);
  res.send({ code: 200 });
});
router.get("/getservice", async (req, res) => {
  let data = await serviceModel.find().lean();
  let obj = {};
  data.forEach((i) => {
    obj[i._id] = i;
  });
  let result = [];
  data.forEach((i) => {
    if (!i.tid) {
      result.push(i);
    }
    if (obj[i.tid] && !obj[i.tid].children) {
      obj[i.tid].children = [];
    }
    obj[i.tid] && obj[i.tid].children.push(i);
  });
  res.send({ code: 200, data: result });
});
router.get("/geiservice", async (req, res) => {
  let data = await serviceModel.find();
  res.send({ code: 200, data });
});

router.post("/addstylist", async (req, res) => {
  console.log(req.body);

  await stylistModel.create(req.body);
  res.send({ code: 200 });
});
// 获取理发师列表
router.get("/getstylist", async (req, res) => {
  let data = await stylistModel.find().populate("salonId");
  res.send({ code: 200, data });
});
// 删除理发师
router.delete('/delstylist/:id',async(req,res)=>{
    const id = req.params.id;

  await stylistModel.deleteOne({_id:id});
  res.send({code:200})
})
// 沙箱支付
router.use(express.urlencoded({ extended: true }));
router.post("/api/payment", (req, res) => {
  let { orderId, totalAmount, subject, passback_params } = req.body;
  const formData = new AlipayFormData();
  formData.setMethod("get"); //设置表单的提交方法为get
  formData.addField("returnUrl", "http://localhost:5173/fuxiang"); //支付成功后跳转的页面
  formData.addField("bizContent", {
    outTradeNo: orderId, //订单号
    productCode: "FAST_INSTANT_TRADE_PAY", //支付渠道
    totalAmount: totalAmount, //支付金额
    subject: subject, //商品名称
    passbackParams: JSON.parse(passback_params), //商品描述
  }); //设置业务参数
  // alipay.trade.wap.pay这个是沙箱支付接口
  const reult = alipaySdk.exec(
    "alipay.trade.wap.pay",
    {},
    { formData: formData }
  );
  reult.then((resp) => {
    res.send({
      code: 200,
      result: resp,
    });
  });
});
router.post("/api/queryOrder", async (req, res) => {
  let { trade_no, out_trade_no } = req.body;
  const formData = new AlipayFormData();
  formData.setMethod("get"); //设置表单的提交方法为get
  formData.addField("bizContent", {
    out_trade_no,
    trade_no,
  }); //设置业务参数
  const reult = alipaySdk.exec(
    "alipay.trade.query",
    {},
    { formData: formData }
  );
  reult.then((resData) => {
    axios({
      url: resData,
      method: "get",
    })
      .then((data) => {
        let r = data.data.alipay_trade_query_response;
        // console.log(r);
        if (r.code == "10000") {
          switch (r.trade_status) {
            case "WAIT_BUYER_PAY":
              res.send({
                code: 200,
                result: "等待支付",
              });
              break;
            case "TRADE_SUCCESS":
              res.send({
                code: 200,
                result: "支付成功",
                out_trade_no: r.out_trade_no,
                total_amout: r.total_amount,
                buyer_login_id: r.buyer_logon_id,
                trade_no: r.trade_no,
                passback_params: JSON.parse(r.passback_params),
              });
              break;
            case "TRADE_CLOSED":
              res.send({
                code: 200,
                result: "交易关闭",
              });
              break;
            case "TRADE_FINISHED":
              res.send({
                code: 200,
                result: "交易结束,不可以退款",
              });
              break;
          }
        } else if (r.code == "40004") {
          //订单不存在
          res.send("订单不存在");
        }
      })
      .catch((err) => {
        res.send({
          code: 200,
          err,
        });
      });
  });
});
//退款
router.post("/api/refund", async (req, res) => {
  let { refund_amount, trade_no } = req.body;
  console.log(refund_amount, trade_no);

  const formData = new AlipayFormData();
  formData.setMethod("get"); //设置表单的提交方法为get
  formData.addField("bizContent", {
    refund_amount,
    trade_no,
  }); //设置业务参数
  const reult = alipaySdk.exec(
    "alipay.trade.refund",
    {},
    { formData: formData }
  );
  reult.then((resp) => {
    axios({
      url: resp,
      method: "get",
    }).then((data) => {
      let r = data.data.alipay_trade_refund_response;
      if (r.code == "10000") {
        res.send({ code: 200, result: "退款成功" });
      } else {
        res.send({ code: 200, result: "退款失败" });
      }
    });
  });
});

//添加订单列表
router.post('/addorder', async (req, res) => {
    await orderModel.create(req.body)
    res.send({ code: 200 })
})//获取订单
router.get('/getorder', async (req, res) => {
    let {page,pagesize}=req.query;
    let data = await orderModel.find().populate('salonId').populate('stylistId').populate('serviceId').populate('packageId').skip((page-1)*pagesize).limit(pagesize)
    // 实现到时间发送通知
    res.send({ code: 200, data })
})//修改订单状态
router.put('/chanremind',async(req,res)=>{
    let {_id}=req.query;
    await orderModel.updateOne({_id},{$set:{remind:true}})
    res.send({code:200})
})
// 改为已使用
router.put('/chanstatus',async(req,res)=>{
    let {_id}=req.query;
    await orderModel.updateOne({_id},{status:1})
    res.send({code:200})
})
// 订单已评价
router.put('/chanpj',async(req,res)=>{
    let {_id}=req.query;
    await orderModel.updateOne({_id},{ispj:true})
    res.send({code:200})
})

router.put('/changeStatus',async(req,res)=>{
    
    let {ids}=req.body;
    await orderModel.updateMany({_id:{$in:ids}},{status:1})
    res.send({
        code:200
    })
})

//已退款
router.put("/chanrefund", async (req, res) => {
  let { _id } = req.query;
  await orderModel.updateOne({ _id }, { status: 2 });
  res.send({ code: 200 });
});

//获取套餐列表
router.post("/addpackage", async (req, res) => {
  await packageModel.create(req.body);
  res.send({ code: 200 });
});
router.get("/getpackage", async (req, res) => {
  let data = await packageModel.find();
  res.send({ code: 200, data });
});

//获取评论列表
router.post('/addreview',async(req,res)=>{
    await reviewModel.create(req.body)
    res.send({code:200})
})
router.get('/getreview',async(req,res)=>{
    let data = await reviewModel.find().populate('userId').populate('stylistId').populate('salonId').populate('serviceId').lean()
    let obj={}
    data.forEach(i=>{
        obj[i._id]=i
    })
    let result=[]
    data.forEach(i=>{
        if(!i.rid){
            result.push(i)
        }
        if(obj[i.rid] && !obj[i.rid].children){
            obj[i.rid].children=[]
        }
        obj[i.rid] && obj[i.rid].children.push(i)
    })
    res.send({code:200,data:result})
})

module.exports = router;
